using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

using Common;

using GrpcClient.Interfaces;

using Newtonsoft.Json;

namespace GrpcClient.Managers
{
    public class ConfigManager : IConfigManager
    {
        public ConfigManager()
        {
            if (!Directory.Exists("config"))
            {
                Directory.CreateDirectory("config");
            }
        }

        public string GetFullPath(string key)
        {
            return Path.Combine("config", key + ".json");
        }

        public T? Read<T>(string key)
        {
            string path = GetFullPath(key);

            if (!File.Exists(path))
            {
                return default(T);
            }
            string content = File.ReadAllText(path);
            return JsonConvert.DeserializeObject<T>(content);
        }

        public void Write<T>(string key, T value)
        {
            string path = GetFullPath(key);

            Formatting formatting = Formatting.Indented;
            var content = JsonConvert.SerializeObject(value, formatting);
            File.WriteAllText(path, content);
        }
    }
}
